package com.yifushidai.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageSerializable;
import com.yifushidai.annotation.UserHolder;
import com.yifushidai.api.DynamicTempkeyTask;
import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.DynamicTempkey;
import com.yifushidai.entity.KeypassBandEntity;
import com.yifushidai.entity.UserEntity;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.KeypassBandEntityMapper;
import com.yifushidai.mapper.PowerEntityMapper;
import com.yifushidai.mapper.UserEntityMapper;
import com.yifushidai.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Service
public class LockService {

    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;
    @Autowired
    private UserEntityMapper userMapper;
    @Autowired
    private KeypassBandEntityMapper keyPassMapper;
    @Autowired
    private IcBindService icBindService;
    @Autowired
    private DynamicTempkeyService dynamicTempkeyService;
    @Autowired
    private PowerEntityMapper powerEntityMapper;

    public R saveMac(String mac, String alias, String addr, Double lat, Double lng, String blueteeth, MultipartFile upLoadFile, HttpServletRequest request) throws ParseException, IOException {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null != one) return R.error(ErrorCodeEnum.DATA_DUPLICATE);

        apiUniqueMacMapper.insertSelective(ApiUniqueMac.builder()
                .mobile(UserHolder.get().getMobile())
                .mac(mac)
                .alias(alias)
                .addr(addr)
                .lat(lat)
                .lng(lng)
                .bluetooth(blueteeth)
//                .img(uploadImg(upLoadFile, request))
                .build());

        //绑定初始密码
        KeypassBandEntity keypassEntity = new KeypassBandEntity();
        keypassEntity.setMac(mac);
        keyPassMapper.insertSelective(keypassEntity);
        return R.ok();
    }

    public R bandPower(String mac, Double eprice, Double pow) throws ParseException, IOException {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        one.setEprice(eprice);
        one.setPow(pow);
        apiUniqueMacMapper.updateByPrimaryKey(one);
        return R.ok();
    }

    public R modImg(MultipartFile img, String mac, HttpServletRequest request) throws IOException {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        if (!FileUtil.isImage(img.getInputStream())) {
            return R.error(ErrorCodeEnum.FILE_TYPE_WRONG);
        }

        String imgUrl = AliyunOSSUtil.getImgUrl(mac, img);
        one.setImg(imgUrl);
        apiUniqueMacMapper.updateByPrimaryKey(one);
        return R.ok().put(imgUrl);
    }

    public R getMainLocks() {
        // 创建Example
        Example example = new Example(ApiUniqueMac.class);
        example.setOrderByClause(" bandtime DESC, id DESC ");

        // 创建Criteria 添加条件
        Example.Criteria criteria2 = example.and();
        criteria2.orEqualTo("mobile", UserHolder.get().getMobile());
        criteria2.orEqualTo("mobile2", UserHolder.get().getMobile());

        List<ApiUniqueMac> list = apiUniqueMacMapper.selectByExample(example);
        return R.ok().put(new PageUtils(list, list.size()));
    }

    public R hasPowerDevice() {
        // 创建Example
        Example example = new Example(ApiUniqueMac.class);
        example.setOrderByClause(" bandtime DESC, id DESC ");

        // 创建Criteria 添加条件
        Example.Criteria criteria2 = example.and();
        criteria2.orEqualTo("mobile", UserHolder.get().getMobile());
        criteria2.orEqualTo("mobile2", UserHolder.get().getMobile());

        List<ApiUniqueMac> list = apiUniqueMacMapper.selectByExample(example);
        for (ApiUniqueMac apiUniqueMac : list) {
            if (StringUtils.isNotBlank(apiUniqueMac.getPowerMac())) {
                return R.ok().put(1);
            }
        }
        return R.ok().put(0);
    }

    public R getBluetooth(String mac) {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        return R.ok().put(one.getBluetooth());
    }

    public R powerofdelay(String mac, Integer powerOfDelay) {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        one.setPowerOfDelay(powerOfDelay);
        apiUniqueMacMapper.updateByPrimaryKey(one);
        return R.ok();
    }

    public R deleteByMac(String mac, HttpServletRequest request) throws InterruptedException {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);
        if (!one.getMobile().equals(UserHolder.get().getMobile())) return R.error(ErrorCodeEnum.MAC_PERMISSION);

        for (Map.Entry<String, ScheduledFuture<?>> e : DynamicTempkeyTask.scheduledFutureConcurrentHashMap.entrySet()) {
            if (e.getKey().startsWith(mac)) {
                e.getValue().cancel(true);
                DynamicTempkeyTask.scheduledFutureConcurrentHashMap.remove(e.getKey());
            }
        }
        DynamicTempkey record = new DynamicTempkey();
        record.setMac(mac);
        dynamicTempkeyService.deleteByMac(record);//动态密码表

        keyPassMapper.deleteByMac(mac);//密码表
        icBindService.deleteByMac(mac);//ic卡绑定表
        apiUniqueMacMapper.delete(ApiUniqueMac.builder().mac(mac).build());//联网mac绑定表

        try {
            Object res = ShisuMinaPushUtils.push(mac, "uniqueMacUnbind:" + mac);
            if ("OK".equals(res)) {
                return R.ok();
            } else {
                return R.error(ErrorCodeEnum.MAC_LOCAL_INIT);
            }
        } finally {
            boolean powerFlag = StringUtils.isNotBlank(one.getPowerMac()) && one.getPowerMac().matches("^\\w{24}$");
            if (powerFlag) {
                ShisuMinaPushUtils.push(one.getPowerMac(), "powerMacUnbind:NA");
            }
        }
    }

    public R listMobile2() {
        List<ApiUniqueMac> apiUniqueMacList = apiUniqueMacMapper.select(ApiUniqueMac.builder().mobile(UserHolder.get().getMobile()).build());
        JSONObject jsonObject = new JSONObject();
        for (ApiUniqueMac one : apiUniqueMacList) {
            if (!jsonObject.containsKey(one.getMobile2())) {
                JSONArray subList = new JSONArray();
                subList.add(one);
                jsonObject.put(one.getMobile2(), subList);
            } else {
                JSONArray subList = jsonObject.getJSONArray(one.getMobile2());
                subList.add(one);
            }
        }
        return R.ok().put(jsonObject);
    }

    public R addMobile2(String param, String mobile2) {
        if (UserHolder.get().getMobile().equals(mobile2)) {
            return R.error(ErrorCodeEnum.DATA_DUPLICATE);
        }
        if (null == userMapper.selectOne(UserEntity.builder().mobile(mobile2).build())) {
            return R.error(ErrorCodeEnum.MOBILE_NULL);
        }
        List<String> macList = JSON.parseArray(param, String.class);
        Example example = new Example(ApiUniqueMac.class);
        Example.Criteria criteria = example.and();
        criteria.andEqualTo("mobile", UserHolder.get().getMobile());
        criteria.andIn("mac", macList);
        return R.ok().put(apiUniqueMacMapper.updateByExampleSelective(ApiUniqueMac.builder().mobile2(mobile2).build(), example));
    }

    public R delMobile2(String mobile2) {
        Example example = new Example(ApiUniqueMac.class);
        Example.Criteria criteria = example.and();
        criteria.andEqualTo("mobile", UserHolder.get().getMobile());
        criteria.andEqualTo("mobile2", mobile2);
        return R.ok().put(apiUniqueMacMapper.updateByExampleSelective(ApiUniqueMac.builder().mobile2("").build(), example));
    }

    public R page(String alias, int offset, int limit) {
        // 创建Example
        Example example = new Example(ApiUniqueMac.class);
        example.setOrderByClause(" bandtime DESC, id DESC ");

        // 创建Criteria 添加条件
        Example.Criteria criteria = example.and();
        if (StringUtils.isNotBlank(alias)) {
            criteria.andLike("alias", "%" + alias + "%");
        }

        Example.Criteria criteria2 = example.and();
        criteria2.orEqualTo("mobile", UserHolder.get().getMobile());
        criteria2.orEqualTo("mobile2", UserHolder.get().getMobile());

        PageHelper.offsetPage(offset, limit);
        List<ApiUniqueMac> list = apiUniqueMacMapper.selectByExample(example);
        return R.ok().put(new PageSerializable(list));
    }

    public R modBluetooth(String mac, String bluetooth) {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        one.setBluetooth(bluetooth);
        return R.ok().put(apiUniqueMacMapper.updateByPrimaryKey(one));
    }

    public R modMobile(String mac, String mobile) {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        one.setMobile(mobile);
        return R.ok().put(apiUniqueMacMapper.updateByPrimaryKey(one));
    }
}
